package com.ws.shop.action.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.bean.Page;
import com.ws.shop.entity.Links;
import com.ws.shop.service.LinksService;
import com.ws.shop.util.RequestUtil;

@Controller
@RequestMapping(value="/admin/links/*")
public class LinksAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(LinksAction.class);
	@Autowired
	private LinksService linksService;
	
	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		try{
			Page page = linksService.findByPage(pageno,0);
			model.addAttribute(Page.PAGE, page);
			model.addAttribute("stateDescs", Links.STATE_DESCS);
			return "links_index";
		}catch(Exception e){
			log.error("查询友情链接失败",e);
			return ERROR;
		}
	}
	
	@RequestMapping(value="input.jhtml",method=RequestMethod.GET)
	public String input(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		if(id > 0){
			Links links = linksService.findLinksById(id);
			model.addAttribute("links", links);
		}
		return "links_input";
	}

	@RequestMapping(value="save.jhtml",method=RequestMethod.POST)
	public String save(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		String title = RequestUtil.getStringParameter(request, "title", null);
		String url = RequestUtil.getStringParameter(request, "url", null);
		int state = RequestUtil.getIntParameter(request, "state", 0);
		int ord = RequestUtil.getIntParameter(request, "ord", 0);
		if(title == null)
			return this.ajaxJsonErrorMessage(response, "友链名称不能为空");
		Links links = new Links(id,title,url,null,state,ord);
		try{
			linksService.saveOrUpdate(links);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+links,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
	
}
